<template>
	<view class="pad-lr-20 pad-tb-20">
		<view class="radius-16 bgfff pad-lr-20">
			<view class="display-sb align-items pad-tb-30">
				<view class="fontSize-30">头像</view>
				<view class="display align-items">
					<view class="avatar-container" @click="chooseImage">
						<image :src="avatar" class="proudct-item-icon-5 border-50" mode="aspectFit"></image>
					</view>
					<image src="/static/img/icon1.png" class="ml10 proudct-item-icon" mode=""></image>
				</view>
			</view>
			<view class="display-sb align-items pad-tb-30">
				<view class="fontSize-30">昵称</view>
				<view class="display align-items">
					<input type="nickname" placeholder="填写昵称"  v-model="nickname" @blur="onNicknameBlur" class="text-align-right"/>
					<image src="/static/img/icon1.png" class="ml10 proudct-item-icon" mode=""></image>
				</view>
			</view>
			<view class="display-sb align-items pad-tb-30">
				<view class="fontSize-30">手机号</view>
				<view class="display align-items">
					<input type="number" placeholder="填写手机号"  v-model="mobile" disabled class="text-align-right"/>
					<image src="/static/img/icon1.png" class="ml10 proudct-item-icon" mode=""></image>
				</view>
			</view>
		</view>
		<view class="bgfff radius-16 mar-top-100 text-align-center edit_btn col-f fontSize-32" @click="_edit_user_info">
			修改
		</view>
		<view class="bgfff radius-16 mar-top-40 text-align-center out_login fontSize-32" @click="out_login">
			退出登录
		</view>
	</view>
</template>

<script lang="ts" setup>
import {saveUser,upload,ApitestUrl} from '@/utils/api'
import { onLoad } from '@dcloudio/uni-app';
import { ref } from 'vue';

// HTML 实体解码函数
const decodeHtmlEntities = (str: string) => {
	if (!str) return str;
	return str.replace(/&amp;/g, '&');
};
onLoad((options: any)=>{
	// 先进行 URL 解码，然后解析 JSON
	let userInfoStr = decodeURIComponent(options?.info || '{}');
	let userInfo: any = {};
	try {
		userInfo = JSON.parse(userInfoStr);
	} catch (error) {
		console.error('JSON 解析失败:', error, '原始数据:', options?.info);
		// 如果解析失败，使用空对象
		userInfo = {};
	}
	
	// 解码 HTML 实体，确保显示正确的 & 符号
	nickname.value = decodeHtmlEntities(userInfo.nickname || '');
	mobile.value = decodeHtmlEntities(userInfo.mobile || '');
	// 使用 avatar_text（完整URL），如果没有则使用 avatar（相对路径）
	avatar.value = decodeHtmlEntities(userInfo.avatar_text || userInfo.avatar || '/static/images/avatar.png');
})
const nickname = ref()
const mobile = ref()
const avatar = ref()
const onNicknameBlur = (e: any) =>{
	const newNickname = e.detail.value;
	if (newNickname && newNickname !== nickname.value) {
		nickname.value = newNickname;
		// 昵称修改后自动保存，确保保存的是解码后的数据
		saveUser({avatar: avatar.value, nickname: decodeHtmlEntities(nickname.value), mobile: mobile.value}).then((res: any) => {
			uni.showToast({
				title: res.msg,
				icon: res.code === 1 ? 'success' : 'none'
			});
		});
	}
}
const chooseImage = () => {
	uni.chooseImage({
		count: 1,
		sizeType: ['compressed'],
		sourceType: ['album', 'camera'],
		success: (res) => {
			const tempFilePath = res.tempFilePaths[0];
			uni.showLoading({
				title: '头像上传中...',
				mask: true
			});
			
			uni.uploadFile({
				url: upload,
				filePath: tempFilePath,
				name: 'file',
				header: {
					'ba-user-token': uni.getStorageSync('token'),
					'server': 1,
				},
				success: (uploadFileRes: any) => {
					uni.hideLoading();
					console.log('上传响应:', uploadFileRes);
					const result = JSON.parse(uploadFileRes.data);
					console.log('解析结果:', result);
					
					if (result.code === 1) {
						const avatarUrl = result.data.file.url;
						console.log('头像URL:', avatarUrl);
						
						// 确保头像URL是完整的URL
						let fullAvatarUrl = avatarUrl;
						if (avatarUrl && !avatarUrl.startsWith('http')) {
							// 如果是相对路径，需要添加域名前缀
							fullAvatarUrl = ApitestUrl.replace('/api', '') + avatarUrl;
						}
						console.log('完整头像URL:', fullAvatarUrl);
						avatar.value = fullAvatarUrl;
						
						// 头像上传成功后自动保存（保存相对路径到后端）
						saveUser({avatar: avatarUrl, nickname: decodeHtmlEntities(nickname.value), mobile: mobile.value}).then((res: any) => {
							console.log('保存用户信息响应:', res);
							uni.showToast({
								title: res.msg,
								icon: res.code === 1 ? 'success' : 'none'
							});
						}).catch((error: any) => {
							console.error('保存用户信息失败:', error);
							uni.showToast({
								title: '保存失败',
								icon: 'none'
							});
						});
					} else {
						console.error('上传失败:', result);
						uni.showToast({
							title: result.msg || '头像上传失败',
							icon: 'none'
						});
					}
				},
				fail: (error: any) => {
					uni.hideLoading();
					uni.showToast({
						title: '头像上传失败',
						icon: 'none'
					});
				}
			});
		},
		fail: (error: any) => {
			console.log('选择图片失败:', error);
		}
	});
}
const _edit_user_info =() =>{
	// 确保保存的是解码后的数据，避免 &amp; 保存到数据库
	saveUser({avatar:avatar.value,nickname:decodeHtmlEntities(nickname.value),mobile:mobile.value}).then((res: any)=>{
		uni.showToast({
			title:res.msg,
			icon:'none'
		})
		if(res.code==1){
			setTimeout(()=>{
				uni.navigateBack({delta:1})
			},1500)
		}
	})
}
const out_login =() =>{
	uni.showModal({
			title:'提示',
			content:'是否退出登录',
			success: function (res) {
					if (res.confirm) {
						// 清除所有用户相关存储
						uni.removeStorageSync('token')
						uni.removeStorageSync('id')
						uni.removeStorageSync('userInfo')
						uni.removeStorageSync('pid')
						uni.removeStorageSync('h5_login_data')  // 清除H5登录数据
						uni.removeStorageSync('h5_token')      // 清除H5 token
						
						// 跳转到首页
						uni.reLaunch({
							url:'/pages/index/index'
						})
					} else if (res.cancel) {
					}
				}
		})
}
</script>

<style lang="scss">
@import 'info.scss';
</style>
